package com.example.doctor.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.example.common.entity.*;
import com.example.common.redis.RedisService;
import com.example.common.support.ApiException;
import com.example.common.utils.IdUtils;
import com.example.doctor.dto.req.*;
import com.example.doctor.dto.resp.*;
import com.example.doctor.jpa.*;
import com.example.doctor.mapper.QaMapper;
import com.example.doctor.service.QaService;
import com.example.doctor.utils.HttpUtils;
import com.example.doctor.utils.UserUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sifan
 * @PackagName:com.example.doctor.service.impl
 * @ClassName: QaServiceImpl
 * @Description:
 * @date:2021/1/26 11:51
 */
@Service
public class QaServiceImpl implements QaService {

    @Resource
    UserUtils userUtils;

    @Resource
    QaMapper qaMapper;

    @Resource
    QuestionMainRepository questionMainRepository;

    @Resource
    HquestionRepository hquestionRepository;

    @Resource
    HanswerRepository hanswerRepository;

    @Resource
    FollowrQuestionMainRepository followrQuestionMainRepository;

    @Resource
    QuestionRepository questionRepository;

    @Resource
    AnswerRepository answerRepository;

    @Resource
    MsgConfigRepository msgConfigRepository;

    @Resource
    DoctorBaseInfoRepository doctorBaseInfoRepository;

    @Resource
    HttpUtils httpUtils;

    @Override
    public Map<String, Object> list(NoticeListReq req) {
        Map<String,Object> result = new HashMap<>();
        List<QaListRsp> qaListRspList = qaMapper.list(userUtils.getUser().getDcId(),(req.getPage()-1)*req.getLimit(),req.getLimit());
        List<QaListRsp> sortList = qaListRspList.stream().sorted((o1, o2) -> {
            return o2.getCreateTime().compareTo(o1.getCreateTime());
        }).collect(Collectors.toList());
        long count =qaMapper.count(userUtils.getUser().getDcId());
        result.put("total",count);
        result.put("list",sortList);
        return result;
    }

    @Override
    public QaInfoRsp Info(QaInfoReq qaInfoReq) {
        QuestionMain questionMain = questionMainRepository.findById(qaInfoReq.getTID()).orElse(null);
        List<Hquestion> hquestions = hquestionRepository.findByTId(questionMain.getTid());
        QaInfoRsp qaInfoRsp = new QaInfoRsp();
        qaInfoRsp.setTName(questionMain.getTName());
        List<QAList> ql = new ArrayList<>();
        for (Hquestion hquestion : hquestions) {
            String[] Answer = qaMapper.queryByQid(hquestion.getQId());
            QAList qaList = new QAList();
            qaList.setQContent(hquestion.getQContent());
            qaList.setQType(hquestion.getQType());
            qaList.setAnswer(Answer);
            ql.add(qaList);
        }
        qaInfoRsp.setQAList(ql);
        return qaInfoRsp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public HashMap<String, Object> SaveQA(SaveQAReq saveQAReq) {
        QuestionMain questionMainDb = questionMainRepository.findById(saveQAReq.getTID()).orElse(null);
        if (ObjectUtils.isEmpty(questionMainDb)) {
            //保存
            Long tId = IdUtils.generateId();
            QuestionMain questionMain = new QuestionMain();
            questionMain.setTName(saveQAReq.getTName());
            questionMain.setDcId(userUtils.getUser().getDcId());
            questionMain.setTid(tId);
            questionMain.setCreateTime(new Date());
            questionMainRepository.save(questionMain);

            List<SaveqaList> qaList = saveQAReq.getQaList();
            for (SaveqaList saveqaList : qaList) {
                //保存问题项
                Long qId = IdUtils.generateId();
                Hquestion hquestion = new Hquestion();
                hquestion.setDcId(userUtils.getUser().getDcId());
                hquestion.setQContent(saveqaList.getQContent());
                hquestion.setQType(saveqaList.getQType());
                hquestion.setTId(tId);
                hquestion.setQId(qId);
                hquestionRepository.save(hquestion);

                if(saveqaList.getQType() != 3){
                    //保存选项答案
                    String[] aItem = saveqaList.getAItem();
                    for (String s : aItem) {
                        Hanswer hanswer = new Hanswer();
                        hanswer.setQId(qId);
                        hanswer.setAId(IdUtils.generateId());
                        hanswer.setTId(tId);
                        hanswer.setAItem(s);
                        hanswerRepository.save(hanswer);
                    }
                }
            }
        } else {
            questionMainDb.setTName(saveQAReq.getTName());
            questionMainRepository.save(questionMainDb);
            //删除选项
            hquestionRepository.deleteByTid(saveQAReq.getTID());
            //删除选项答案
            hanswerRepository.deleteByTid(saveQAReq.getTID());
            List<SaveqaList> qaList = saveQAReq.getQaList();
            for (SaveqaList saveqaList : qaList) {
                //保存问题项
                Long qId = IdUtils.generateId();
                Hquestion hquestion = new Hquestion();
                hquestion.setDcId(userUtils.getUser().getDcId());
                hquestion.setQContent(saveqaList.getQContent());
                hquestion.setQType(saveqaList.getQType());
                hquestion.setTId(saveQAReq.getTID());
                hquestion.setQId(qId);
                hquestionRepository.save(hquestion);
                if(saveqaList.getQType() != 3){
                //保存选项答案
                    String[] aItem = saveqaList.getAItem();
                    for (String s : aItem) {
                        Hanswer hanswer = new Hanswer();
                        hanswer.setQId(qId);
                        hanswer.setAId(IdUtils.generateId());
                        hanswer.setTId(saveQAReq.getTID());
                        hanswer.setAItem(s);
                        hanswerRepository.save(hanswer);
                    }
                }
            }
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        return hashMap;
    }

    @Override
    public HashMap<String, Object> Del(DelReq delReq) {
        questionMainRepository.deleteById(delReq.getTID());
        hquestionRepository.deleteByTid(delReq.getTID());
        hanswerRepository.deleteByTid(delReq.getTID());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        return hashMap;
    }

    @Override
    public  Map<String,Object> Notes(NoticeListReq req) {
        Map<String,Object> result = new HashMap<>();
        List<NotesRsp> notesRspLists = new ArrayList<>();
        List<String> fCodes = qaMapper.groupFcodes(userUtils.getUser().getDcId());
        for (String fCode : fCodes) {
            List<NotesRsp> notesRspList = qaMapper.findByFcode(fCode);
            NotesRsp notesRsp =notesRspList.get(0);
            notesRsp.setFCount(notesRspList.size());
            notesRspLists.add(notesRsp);
        }
        List<NotesRsp> collect = notesRspLists.stream().sorted(Comparator.comparing(NotesRsp::getCreateTime, (d1, d2) -> d2.compareTo(d1))).collect(Collectors.toList());
        long count = collect.stream().count();
        List<NotesRsp> list = collect.stream().skip((req.getPage()-1)*req.getLimit()).limit(req.getLimit()).collect(Collectors.toList());
        result.put("total",count);
        result.put("list",list);
        return result;
    }

    @Override
    public TakePartRsp TakePart(TakePartReq takePartReq) {
        List<TakePartListRsp> takePartListRspList = qaMapper.findByFcodeTake(userUtils.getUser().getDcId(),takePartReq.getFCode());
        if (ObjectUtils.isEmpty(takePartListRspList)){
            return null;
        }
        for (TakePartListRsp takePartListRsp : takePartListRspList) {
            takePartListRsp.setAge(DateUtil.betweenYear(takePartListRsp.getBirthday(),new Date(),false));
        }
        TakePartRsp takePartRsp = new TakePartRsp();
        takePartRsp.setTName(takePartListRspList.get(0).getTName());
        takePartRsp.setFCount(takePartListRspList.size());
        takePartRsp.setTakePartListRsp(takePartListRspList);
        return takePartRsp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public HashMap<String, Object> Send(SendReq sendReq) {
        Long dcId = userUtils.getUser().getDcId();

        List<String> Pids = null;
        if (sendReq.getSendType().equals(2)) {
            Pids =Arrays.stream(sendReq.getPID().split(",")).collect(Collectors.toList());
        }else if (sendReq.getSendType().equals(1)){
            Pids = qaMapper.queryPidByDcId(dcId);
        }
        String Fcode = "F"+System.currentTimeMillis();
        Long Fid = 0L;
        for (String Pid : Pids) {
            Fid = IdUtils.generateId();
            FollowrQuestionMain followrQuestionMain = new FollowrQuestionMain();
            followrQuestionMain.setFid(Fid);
            followrQuestionMain.setAnswer(false);
            followrQuestionMain.setDcId(dcId);
            followrQuestionMain.setCreateTime(new Date());
            followrQuestionMain.setTName(sendReq.getTName());
            followrQuestionMain.setPid(Long.parseLong(Pid));
            followrQuestionMain.setSendType(sendReq.getSendType());
            followrQuestionMain.setOrderNO(sendReq.getOrderNO());
            followrQuestionMain.setFCode(Fcode);
            followrQuestionMainRepository.save(followrQuestionMain);

            //保存问题选项
            List<Hquestion> hquestionList = hquestionRepository.findByTId(sendReq.getTID());
            for (Hquestion hquestion : hquestionList) {
                Question question = new Question();
                question.setQid(hquestion.getQId());
                question.setFid(Fid);
                question.setId(IdUtils.generateId());
                question.setQContent(hquestion.getQContent());
                question.setQType(hquestion.getQType());
                questionRepository.save(question);

                if(question.getQType() == 3){
                    Answer answer = new Answer();
                    answer.setAid(0l);
                    answer.setFid(Fid);
                    answer.setId(IdUtils.generateId());
                    answer.setChk(false);
                    answer.setQid(hquestion.getQId());
                    answer.setAItem("");
                    answerRepository.save(answer);
                    continue;
                }

                List<Hanswer> hanswerList = hanswerRepository.findByQid(hquestion.getQId());
                for (Hanswer hanswer : hanswerList) {
                    Answer answer = new Answer();
                    answer.setAid(0l);
                    answer.setFid(Fid);
                    answer.setId(IdUtils.generateId());
                    answer.setChk(false);
                    answer.setQid(hquestion.getQId());
                    answer.setAItem(hanswer.getAItem());
                    answerRepository.save(answer);
                }
            }
        }
        //给患者发 随访提醒
//        String key ="Client_FollowrRemind";
//        MsgConfig msgConfig = msgConfigRepository.findByKey(key);
//        List<Client_FollowrRemind> client_followrReminds = qaMapper.Client_FollowrRemind(Fcode);
//
//        if (client_followrReminds.size()>0) {
//            DoctorBaseInfo doctorBaseInfo = doctorBaseInfoRepository.findByDcId(client_followrReminds.get(0).getDCID());
//
//            //发送模板
//            //获取token
//            String url = "https://api.weixin.qq.com/cgi-bin/token";
//            HashMap<String, String> map = new HashMap<>();
//            map.put("grant_type", "client_credential");
//            map.put("appid", "");//TODO
//            map.put("secret", "");
//            Map<String, Object> stringObjectMap = httpUtils.get(url, map);
//            String access_token = stringObjectMap.get("access_token").toString();
//
//            WxMpService wxMpService = new WxMpServiceImpl();
//            WxMpDefaultConfigImpl wxMpConfigStorage = new WxMpDefaultConfigImpl();
//            wxMpConfigStorage.setAppId("");//TODO
//            wxMpConfigStorage.setSecret("");//TODO
//            wxMpConfigStorage.setAccessToken(access_token);
//            wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
//
//            //发送模板消息
//            for (Client_FollowrRemind client_followrRemind : client_followrReminds) {
//                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().toUser(client_followrRemind.getOpenID()).templateId(msgConfig.getTemplateId()).url("").build();
//                templateMessage.addData(new WxMpTemplateData("first", doctorBaseInfo.getName()+"医生向您发送了1条随访，请尽快填写，帮助医生跟踪了解您的情况", ""));
//                templateMessage.addData(new WxMpTemplateData("keyword1", client_followrRemind.getName(), ""));
//                templateMessage.addData(new WxMpTemplateData("keyword2", DateUtil.format(client_followrRemind.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN), ""));
//                templateMessage.addData(new WxMpTemplateData("keyword3", client_followrRemind.getTName(), ""));
//                templateMessage.addData(new WxMpTemplateData("remark", "", ""));
//                try {
//                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
//                } catch (WxErrorException e) {
//                    throw  new ApiException(400,"模板发送失败");
//                }
//            }
//        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Save", true);
        hashMap.put("FID", Fid);
        return hashMap;
    }

    @Override
    public BackRsp Back(BackReq backReq) {
        FollowrQuestionMain followrQuestionMain = followrQuestionMainRepository.findById(backReq.getFID()).orElse(null);
        BackRsp backRsp = new BackRsp();
        backRsp.setTName(followrQuestionMain.getTName());
        List<Question> questionList = questionRepository.findByFid(followrQuestionMain.getFid());
        List<QAListBackRsp> qaList = new ArrayList<>();
        for (Question question : questionList) {
            QAListBackRsp qaListBackRsp = new QAListBackRsp();
            qaListBackRsp.setQContent(question.getQContent());
            qaListBackRsp.setQType(question.getQType());
            qaList.add(qaListBackRsp);
            List<AnswerBackRsp> answer =new ArrayList<>();
            List<Answer> answerList = answerRepository.findByFid(followrQuestionMain.getFid(), question.getQid());
            for (Answer answer1 : answerList) {
                AnswerBackRsp answerBackRsp = new AnswerBackRsp();
                answerBackRsp.setChk(answer1.getChk());
                answerBackRsp.setAItem(answer1.getAItem());
                answer.add(answerBackRsp);
            }
            qaListBackRsp.setAnswer(answer);
        }
        backRsp.setQAList(qaList);
        return backRsp;
    }
}
